import { defineStore } from 'pinia'
import { myListData, getProfile } from '../api/auth/index'
import { useWebSocketStore } from './websocket'

export const useAuthStore = defineStore('auth', {
    state: () => ({
        token: localStorage.getItem('token') || '',
        userInfo: JSON.parse(localStorage.getItem('userInfo')) || null,
        userId: localStorage.getItem('userId') || null,
        roleGroup: localStorage.getItem('roleGroup') || null,
    }),
    actions: {
        setToken(token) {
            this.token = token
            localStorage.setItem('token', token)
        },
        clearToken() {
            this.token = ''
            localStorage.removeItem('token')
        },
        setUserInfo(userInfo) {
            this.userInfo = userInfo.data
            this.userId = userInfo.data?.userId || null
            this.roleGroup = userInfo.roleGroup
            localStorage.setItem('userInfo', JSON.stringify(userInfo.data))
            if (this.userId) {
                localStorage.setItem('userId', this.userId)
            } else {
                localStorage.removeItem('userId')
                console.warn('⚠️ 用户信息中未找到userId')
            }
            localStorage.setItem('roleGroup', userInfo.roleGroup || '')
        },
        async fetchUserInfo() {
            try {
                const response = await getProfile()
                if (response.code === 200) {
                    this.setUserInfo(response)
                    return Promise.resolve(response)
                } else {
                    return Promise.reject(response.message || 'Failed to fetch user info')
                }
            } catch (error) {
                return Promise.reject(error)
            }
        },
        async login(credentials) {
            try {
                const response = await myListData(credentials)
                if (response.code === 200) {
                    this.setToken(response.token)
                    const userInfo = await this.fetchUserInfo()

                    const wsStore = useWebSocketStore()
                    wsStore.handleAuthChange(this.token, this.userId)

                    return Promise.resolve(response)
                } else {
                    return Promise.reject(response.message || 'Login failed')
                }
            } catch (error) {
                return Promise.reject(error)
            }
        },
        async logout() {
            const wsStore = useWebSocketStore()
            if (!wsStore.isClearingNotifications) {
                wsStore.clearAllNotifications()
            }
            wsStore.disconnectWebSocket()
            this.clearToken()
            this.userInfo = null
            this.userId = null
            this.roleGroup = null
            localStorage.removeItem('userInfo')
            localStorage.removeItem('userId')
            localStorage.removeItem('roleGroup')
        },

        initAuthFromStorage() {
            this.token = localStorage.getItem('token') || ''
            this.userId = localStorage.getItem('userId') || null
            this.roleGroup = localStorage.getItem('roleGroup') || null
            try {
                const storedUserInfo = localStorage.getItem('userInfo')
                if (storedUserInfo) {
                    this.userInfo = JSON.parse(storedUserInfo)
                    if (this.userInfo?.userId) {
                        this.userId = this.userInfo.userId
                        localStorage.setItem('userId', this.userId)
                    }
                }
            } catch (e) {
                console.error('解析本地用户信息失败:', e)
                this.userInfo = null
            }

            if (this.token && this.userId) {
                const wsStore = useWebSocketStore()
                wsStore.handleAuthChange(this.token, this.userId)

                if (window.authAPI?.setAuthToken) {
                    window.authAPI.setAuthToken(this.token)
                }
            }
        }
    }
})
